<?php
  //ini_set('display_errors',1);
  //error_reporting(E_ALL);

  header('Content-type: application/json');
  header('Access-Control-Allow-Origin: *');

  if (empty($_GET['player'])) die(preg_replace('/[\r\n\t]+/', ' ', file_get_contents('resources/player.json')));
  
  $player = new stdClass();
  $player->name = substr(preg_replace('/[^a-zA-Z0-9]+/', '', strtolower($_GET['player'])), 0, 9);
  $player->game = ((isset($_GET['game'])) ? $_GET['game'] : 'ra2');

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'http://xwis.net/'. $player->game .'/pl/'. $player->name .'/');
  curl_setopt($ch, CURLOPT_HEADER, 0); 
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  curl_setopt($ch, CURLOPT_ENCODING, '');
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); 
  $buffer = curl_exec($ch);
  curl_close($ch);

  if (empty($buffer)) die(header('HTTP/1.0 504 Gateway Time-out'));
  if (preg_match('/404 - Not Found/', $buffer)) die(header('HTTP/1.0 404 Not Found'));
  preg_match_all('/<hr><div style="float: right;">(.*?)<\/div>/ism', $buffer, $match);
  //printf('<pre><div style="display:none;">%s</div></pre>', print_r($match, 1));

  preg_match_all('/[^<div style="float: right;">](.*?)<br>/', $match[0][0], $stats);
  //printf('<pre><div style="display:none;">%s</div></pre>', print_r($stats, 1));

  foreach($stats[0] as $key => $value) {
    $value = strip_tags($value);
    if (substr($value, -3) == 'FPS') $player->fps = (int)substr($value, 0, -4);
    if ($value[0] == '#') {
        $x = explode(' ', $value);
        $player->ladder = (int)substr($x[0], 1);
        $player->wins = (int)$x[1];
        $player->losses = (int)$x[3];
        $player->points = (int)substr($x[4], 0, -1);
    }
    if (substr($value, -11) == 'disconnects') $player->discon = (int)substr($value, 0, -12);
    if (substr($value, -6) == 'errors') $player->recon = (int)substr($value, 0, -20);
    if (preg_match('/days|hours|minutes/', $value)) $player->time = explode(' ', $value);
  }

  //$player->url = 'http://xwis'. ((isset($_GET['site']) ? '.net' : '.us')) .'/'. $player->game .'/pl/'. $player->name .'/';

  preg_match_all('/([\d]{1,})x<td class=ac><img src=".*?" alt="([\w\d\s]{1,})"[^>]+>/', $match[1][0], $stats);

  foreach($stats[2] as $key => $name) $player->countries[$name] = (int)$stats[1][$key];

  //printf('<pre><div style="display:none;">%s</div></pre>', print_r($match[1][0], 1));

  preg_match_all('/([\d]{1,})x<td>([\w\d\s]{1,})/', $match[1][0], $stats);

  foreach($stats[2] as $key => $name) $player->maps[$name] = (int)$stats[1][$key];

  preg_match_all('/<a *[^>]+>([\d]{1,})<\/a>.*? alt="([\w\d\s]{1,})" .*?<td>([W|L])<td class=ar>([-|+][\d]{1,}).*? alt="([\w\d\s]{1,})" .*?<a *[^>]+>([\w\d]{1,})<\/a>.*?<td class=ar>([-|+][\d]{1,}).*?([\d:]{2,})<td>([\w\d\s]{1,})<td class=ar>(.*?)</', $buffer, $games);
  //printf('<pre>%s</pre><br /><br />', print_r($games, 1));

  foreach($games[1] as $key => $gid) {
    $player->games[] = array(
      'gid' => (int)$gid,
      'player_country' => $games[2][$key],
      'resolution' => $games[3][$key],
      'player_points' => (int)trim($games[4][$key], '-+'),
      'opponent_country' => $games[5][$key],
      'opponent' => $games[6][$key],
      'opponent_points' => (int)trim($games[7][$key], '-+'),
      'duration' => $games[8][$key],
      'map' => $games[9][$key],
      'timestamp' => strtotime($games[10][$key]),
    );
  }

  include 'mysql.php';
  $data = addslashes(serialize($player));
  @$mysqli->query('INSERT INTO `dump` (`service`, `game`, `timestamp`, `data`) VALUES ("player", "'. addslashes($player->game) .'", '. time() .',"'. $data.'")');
  @$mysqli->close();
  die(json_encode($player));
?>